import { logout, } from '@/api/user'
import { login,getUserInfo,getMoveRouter } from '@/api/index'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    menus:''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_MENU: (state,menus) => {
    state.menus = menus
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { loginame, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ loginame: loginame.trim(), password: password }).then(response => {
        commit('SET_TOKEN', response.token)
        setToken(response.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    // console.log(111);
    // return
    return new Promise((resolve, reject) => {
      getUserInfo().then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { loginame } = data

        commit('SET_NAME', loginame)
        commit('SET_AVATAR', 'https://pic2.zhimg.com/80/v2-d811c2f232e21afdbc1b40dd06125eda_720w.jpg?source=1940ef5c')
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

    // get route
    getRoute({ commit, state }) {
      // console.log(111);
      // return
      return new Promise((resolve, reject) => {
        getMoveRouter().then(response => {
          const menus = response.data
          menus.push({
            path:'/404',
            component:'404',
            hidden:true
          },{
            path:'*',
            component:'404',
            hidden:true
          })


          commit('SET_MENU', menus)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
        // 模拟退出
        console.log("out")
            removeToken() // must remove  token  first
    //   logout(state.token).then(() => {
        resetRouter()
        commit('RESET_STATE')
        resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

